package slidingWindow;

import java.util.HashMap;
import java.util.HashSet;

public class lengthOfLongestSubstring {
    // 法一：直接双重for，n^2复杂度
    public static int lengthOfLongestSubstring1(String s) {
        if (s.length() == 0) {
            return 0;
        } else if (s.length() == 1) {
            return 1;
        }
        return 0;
    }

    // 法二：滑动窗口+hashmap
    // 但其实不是滑动窗口，对于全重复的字符串，如“aaaaaaaa”,复杂度为on^2,关键问题在于map的重新初始化
    public static int lengthOfLongestSubstring2(String s) {
        if (s.length() == 0) {
            return 0;
        } else if (s.length() == 1) {
            return 1;
        }
        // left记录着起始位置
        int left = 0, right = 0, count = 0, max = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        for (right = 0; right < s.length(); right++) {
            if (right >= s.length()) {
                break;
            }
            Character currentChar = s.charAt(right);
            Integer index = map.get(currentChar);
            if (index == null) {
                map.put(currentChar, right);
                count++;
            } else {
                // 更新当前字符的起始位置
                // abdbacbb
                left = index + 1;
                // 重新初始化map
                map = new HashMap<>();
                for (int i = left; i <= right; i++) {
                    map.put(s.charAt(i), i);
                }
                max = Math.max(count, max);
                count = right - left + 1;
            }

        }
        // 有可能一个重复的都没有，没有更新max
        return Math.max(max, count);
    }

    // 法三：滑动窗口+hashmap
    // 去除map重新初始化操作
    public static int lengthOfLongestSubstring3(String s) {
        if (s.length() == 0) {
            return 0;
        } else if (s.length() == 1) {
            return 1;
        }
        // left记录着起始位置
        int left = 0, right = -1, count = 0, max = 0;
        int length = s.length();
        HashSet<Character> set = new HashSet<>();
        while (left<length) {
            if (left!=0) {
                set.remove(s.charAt(left-1));
            }
            while (right<length-1&&!set.contains(s.charAt(right+1))) {
                set.add(s.charAt(right+1));
                right++;
            }
            //出现重复的，计算当前的长度
            count=right-left+1;
            max=Math.max(max, count);
            left++;
        }
        return max;
    }

    public static void main(String[] args) {
        // String s = "abdbacbb";
        String s = "au213";
        int rs = lengthOfLongestSubstring3(s);
        System.out.println("length=" + rs);
    }
}
